package org.team4.dao;

import java.lang.reflect.Method;

import org.hibernate.SessionFactory;

import org.team4.dao.GenericDAO;


/**
 * <p>程序名称：       DAOFactory.java</p>
 * <p>程序说明：       DAO工厂类</p>
 * <p>版权信息：       Copyright 深圳市维远泰克科技有限公司</p>
 * <p>时间：          Jan 7, 2011 4:03:51 PM</p>	
 * 
 * @author：          Marker.King
 * @version：         Ver 0.1
 */
public class DAOFactory {
    
	/**
	 * 创建DAO
	 * @param sessionFactory
	 * @param obj 如果想获得GenericDAO，该参数请传泛型Domain类；<br/>如果想获得具体DAO，该参数请传具体DAO类
	 * @return
	 */
	public static Object getDAO(SessionFactory sessionFactory, Class clazz) {
		Object dao = null;
		if(GenericDAO.class.equals(clazz.getSuperclass())) {
			dao = createDAO(sessionFactory, clazz.getName());
		} else {
			dao = createDAO(sessionFactory, clazz);
		}
		return dao;
	}
	
    /**
     * 创建GenericDAO实例
     * @param sessionFactory
     * @param domainClass
     * @return
     */
    private static Object createDAO(SessionFactory sessionFactory, Class domainClass) {
        try {
            Object dao = null;
            dao = GenericDAO.getInstance(sessionFactory, domainClass);
            return dao;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 创建具体DAO实例
     * @param sessionFactory
     * @param daoClassName
     * @return
     */
    private static Object createDAO(SessionFactory sessionFactory, String daoClassName) {
        try {
            Object dao = null;
            Class daoClass = Class.forName(daoClassName);
            Class paramTypes[] = new Class[]{SessionFactory.class};
            Object paramValues[] = new Object[]{sessionFactory};
            Method method = daoClass.getMethod("getInstance", paramTypes);
            dao = method.invoke(daoClass, paramValues);
            return dao;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
}